# @Desc: 自动交易
import random

from account.trade import exec_buy, exec_sell
from libs.common import success
from trade.models.goods import Goods
from trade.models.robots import Robots


def auto_trade(request):
    return exec_auto_trade()


def exec_auto_trade():
    robots = Robots.objects.filter(deleted=0, status=1).all()
    for item in robots:
        member_id = item.member_id
        goods_sn = item.symbol
        min_vol = item.min_vol
        max_vol = item.max_vol
        amount = min_vol
        if min_vol != max_vol:
            if min_vol > max_vol:
                min_vol, max_vol = max_vol, min_vol
            amount = random.randint(min_vol, max_vol)
        price_fluctuation = random.randint(1, 10)
        db_goods = Goods.objects.filter(sn=goods_sn).values('price').get()
        price = db_goods.get('price')
        if random.randint(0, 1) > 0:
            price = price + price_fluctuation
        else:
            price = price - price_fluctuation
        if price <= 0:
            price = random.randint(1, 10)
        if item.trade_side == 1:
            exec_buy(member_id, goods_sn, amount, price)
        elif item.trade_side == 2:
            exec_sell(member_id, goods_sn, amount, price)
    return success()
